<?php
$masterView = MasterView::getInstance();
$folder = Folder::withId($masterView->streamView->model->folderId);
$folderType = $folder->folderType;
$twitter = Twitter::getTwitters();
$facebook = Facebook::getFacebooks();
$google = Google::getGoogles();
$linkedin = LinkedIn::getLinkedIns();
if (!is_array($masterView->streamView->signals))
    return;
for ($i = 0; $i < count($masterView->streamView->signals); $i++) :
    $mItem = $masterView->streamView->signals[$i];
    $messageId = $mItem->message->getId();
    $streamId = $masterView->streamView->model->streamId;
    $threadId = $mItem->message->getThreadId();
    $messageActionData = MessageAction::getByMessageId($threadId, $streamId);
    if (!isset($_REQUEST['filter'])) {
        if ($messageActionData[2] || $messageActionData[3] || $messageActionData[4])
            continue;
    }
    else {
        $continue = 0;
        if (strpos($_REQUEST['filter'], '/')) {
            $filters = explode('/', $_REQUEST['filter']);
            $_REQUEST['filter'] = $filters[0];
        }
        switch ($_REQUEST['filter']) {
            case 'favorite':
                if (isset($messageActionData[2]) || isset($messageActionData[3]) || isset($messageActionData[4])) {
                    $continue = 1;
                }
                break;
            case 'archive':
                if ($messageActionData[3] || $messageActionData[4])
                    $continue = 1;
                break;
            case 'spam':
                if ($messageActionData[2] || $messageActionData[4])
                    $continue = 1;
                break;
            case 'trash':
                break;
        }
        if ($continue)
            continue;
    }

    if ($messageId < 10) {
        $messageId = $mItem->messageID;
    }
    $mentionStyle = '';
    if ($mItem->message->getSource() == 'www.facebook.com') {
        $postParams = explode('/', $mItem->message->getURL());
        $postData = $postParams[5];
        $data = explode('?comment_id=', $postData);
        $fbUserId = $postParams[3];
        $postId = $data[0];
        $mentionStyle .= 'padding-left: 85px';
    }
    $videoId = '';
    if ($mItem->message->getSource() == 'www.youtube.com') { //Parse youtube links
        $url = $mItem->message->getURL();
        $urlParams = explode('?v=', $url);
        $videoIdTemp = $urlParams[1];
        $idParams = explode('&', $videoIdTemp);
        $videoId = $idParams[0];
        $embedUrl = "https://youtube.googleapis.com/v/" . $videoId;
    }
    if ($mItem->image != '') {
        $mentionStyle .= 'padding-right: 105px';
    }
    if (count($mItem->leadData['replies']) > 0) {
        $mItem->date = $mItem->leadData['replies'][0]['time'];
    }
    $timestamp = $mItem->date->format("U");
    
    $smsTitle = substr($mItem->message->getThreadTitle(),0,50);
    $smsSource = str_replace('www.', '', $mItem->message->getSource());
    $smsDate = $mItem->date->format('d/m/Y');
    $smsTime = $mItem->date->format('h:i A');
    $smsURL = $mItem->message->getURL();
    $smsContent = "[BUZZMETRICS ALERT] Message triggers alarm: '$smsTitle' on $smsSource, $smsDate, $smsTime\r\n$smsURL";
    $shortText = '';
    ?><li class="stream" threadid="<?php echo $threadId; ?>" messageid="<?php echo $messageId;?>">
        <div class="mention-head" replies="">
            <div>
                <img class="social" src="Images/icon-<?php echo StreamController::getSMTIcon($mItem->type); ?>.png" alt="">
                <a class="title" text="<?php echo $mItem->message->getThreadTitle(); ?>" href="<?php echo $mItem->message->getURL(); ?>" target="_blank">
                    <?php echo $mItem->message->getThreadTitle(); ?>
                </a>
            </div>

            <div class="info">
                    <img src="http://www.google.com/s2/favicons?domain=<?php echo $mItem->message->getSource(); ?>" alt="">
                    <p class="link"><span class="source" text="<?php $parse = parse_url($mItem->message->getURL());
                                        $parsedSource = str_ireplace('www.', '', $parse["host"]);
                                        echo $parsedSource; ?>"><?php echo $parsedSource; ?></span><span>|</span><span class="author" text="<?php echo $mItem->message->getLeadAuthor(); ?>"><?php echo $mItem->message->getLeadAuthor(); ?></span></p>
                    <span class="social">
                        <img src="Images/comment.png" alt=""> <p><?php echo $mItem->totalReplies ?></p> &nbsp;
                        <img src="Images/like.png" alt=""> <p><?php echo $mItem->message->getNumberOfLikes() ?></p> &nbsp;
                    </span>
                    <p class="date-time" data-timestamp="<?php echo $timestamp; ?>"><?php echo $mItem->date->format("M d Y h:m A"); ?></p>
            </div>

            <div class="content" text='<?php
                $text = trim(rtrim($mItem->lead, 'null'));
                $text = str_replace('(javascript:void(0))', '', $text);
                $text = str_replace("\n", "<br>", $text);
                eregi("<blockquote>(.*)</blockquote>", $text, $data);
                $blockQuote = $data[0];
                $text = str_replace($blockQuote, "{blockquote}", $text);
                $threadId = $mItem->message->getThreadId();
                $data = Sentiment::saveSentiment(Signal::removeLink($text), $masterView->streamView->model->streamId, $messageId, $threadId, $mItem->message->getTime(), $mItem->type, $mItem->message->getSource());
                $sentimentScore = $data["score"];
                $sentimentText = $data["text"];
                $sentimentColor = $data["color"];
                echo Signal::parseLinks(str_replace("{blockquote}", $blockQuote, $text));
            ?>'>
            <?php if (substr_count($text, " ") > 100) {
                //find the 100th char(' ')
                $endpos = 120;
                $endpos = strpos($text, " ", $endpos);
                $shortText = substr($text, 0, $endpos);
                echo Signal::parseLinks(str_replace("{blockquote}", $blockQuote, $shortText));
            ?>
                    <span class="readmore-threedot">...</span>
                <?php
            } else {
                echo Signal::parseLinks(str_replace("{blockquote}", $blockQuote, $text));
            }?>
            </div>
            <div class="tag-bar hide">
                <div class="tag-zone tag-zone-hide" id="tag-zone">
                    <div class="tag threedot hide"><div class="name"><i class="fa fa-sort"></i></div></div>
                    <?php
                        foreach ($mItem->findTag() as $tag) {
                            echo '<div class="tag"><div class="name">#' . $tag->tagName . '</div><div class="del">x</div></div>';
                        }
                    ?>
                </div>
            </div>
        </div>
            <ul class="mention-content hide">
            <?php
                if (count($mItem->leadData["replies"])) {
                    $count = 0;
                    foreach ($mItem->leadData["replies"] as $reply):
                        $author = $reply['author'];
                        $replyText = Signal::removeLink($reply['text']);
                        if ($author == '')
                            $author = 'Someone';
                ?>
                        <li class="buzz buzz-comment">
                            <div class="comment-detail">
                                <span class="name"><?php echo $author; ?>: </span>
                                <?php 
                                    $replyText = rtrim($replyText, '<br');
                                    $replyText = trim($replyText, 'quote<br><br>');
                                    $threadId = $mItem->message->getThreadId();
                                    $data = Sentiment::saveSentiment($replyText, $masterView->streamView->model->streamId, $reply['messageId'], $threadId, $mItem->message->getTime(), $mItem->type, $mItem->message->getSource());
                                    $sentimentScore = $data["score"];
                                    $sentimentText = $data["text"];
                                    $sentimentColor = $data["color"];
                                    if (strlen($replyText) > 150) {
                                        $endpos = 150;
                                        $endpos = strpos($replyText, " ", $endpos);
                                        if (!$endpos) {
                                            $endpos = strlen($replyText);
                                            ?><span><?php
                                                echo $replyText;
                                                ?></span>
                                            <?php
                                            } else {
                                                echo substr($replyText, 0, $endpos);
                                            ?>
                                            <span class="readmore-threedot">...</span>
                                            <span class="readmore spanshow" onclick="expand(this);" style="color: orange; cursor: pointer; white-space: nowrap;">Read more</span>
                                            <span class="readmore-content hide"><?php echo substr($replyText, $endpos); ?></span>
                                            <span class="readmore spanshow hide" onclick="unexpand(this);" style="color: orange; cursor: pointer; white-space: nowrap;">Show less</span>
                                            <?php
                                        }
                                    } else {
                                        echo $replyText;
                                    }
                                ?>
                            </div>

                            <div class="info">
                                <span class="social">
                                    <img src="Images/like.png" alt=""> <p><?php echo $mItem->message->getNumberOfLikes(); ?></p> &nbsp;
                                </span>
                                <p class="date-time"><?php echo $reply['time']->format("M d Y h:m A"); ?></p>
                            </div>
                        </li>
            <?php endforeach;
                }
            ?>
            </ul>
        </li>
<?php endfor;